package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;

// Assuming TI and Date_time_s are already defined in Java and have similar methods as in TypeScript
// Also assuming ReverseByteArrayOutputStream and ReverseByteArrayInputStream are defined with similar functionality

public class TimeTag extends AxdrType {
    private ByteBuffer dataCode = null;
    private TI ti = null;
    private DateTimeS dts = null;

    public TimeTag() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = ByteBuffer.wrap(dataCode);
    }

    public void setDtsTi(DateTimeS dts, TI ti) {
        this.dts = dts;
        this.ti = ti;
    }

    public void setDTS(DateTimeS dts){
        this.dts = dts;
    }

    public void setTI(TI ti){
        this.ti = ti;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.dts = new DateTimeS();
        codeLength += this.dts.decode(input);
        this.ti = new TI();
        codeLength += this.ti.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.array().length;
            for (int i = this.dataCode.array().length - 1; i >= 0; i--) {
                output.write(this.dataCode.array()[i]);
            }
        } else {
            if (this.ti != null && this.dts != null) {
                codeLength = 0;
                codeLength += this.ti.encode(output);
                codeLength += this.dts.encode(output);
            } else {
                throw new RuntimeException("ti or dts is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        int codeLength = this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(Arrays.copyOfRange(revOStream.toByteArray(), 0, codeLength));
    }

    @Override
    public String toString() {
        if (this.ti != null && this.dts != null) {
            return "sequence: {" + "dts: " + this.dts.toString() + ", ti: " + this.ti.toString() + "}";
        } else {
            return "ti or dts is null";
        }
    }
}



